# -*- coding: utf-8 -*-

import logging

from .models import ChessGrp
from .models import ChessStep
from .models import ChessUser


def get_user_by_session(session_id):
    try:
        return ChessUser.objects.get(session_id=session_id)
    except ChessUser.DoesNotExist:
        logging.warning('user(session_id=%s) is not exist!', session_id)
        return None


def get_lastest_chessgrp():
    grp = None
    try:
        _grp = ChessGrp.objects.latest('grp_id')
        if _grp.grp_members >= 2:
            grp = ChessGrp(grp_members=0)
            grp.save()
        else:
            grp = _grp
    except ChessGrp.DoesNotExist:
        logging.warning('chess group is not exist!')
        grp = ChessGrp(grp_members=0)
        grp.save()
    return grp


def get_chess_steps(pos_x, pos_y, grp):
    try:
        return ChessStep.objects.get(pos_x=pos_x, pos_y=pos_y, grp=grp)
    except ChessStep.DoesNotExist:
        logging.warning('chess step is not exist!')
        return None


def lastest_chess_step(grp):
    try:
        return ChessStep.objects.filter(grp=grp).latest('step')
    except ChessStep.DoesNotExist:
        logging.warning('chess step is not exist!')
        return None


def next_chess_step(grp):
    lastest_step = lastest_chess_step(grp)
    _next = 0
    if lastest_step is not None:
        _next = lastest_step.step
    _next += 1
    return _next
